<template>
    		<section class="todoapp">
			<header class="header">
				<h1>todos</h1>
				<input v-model.trim="content" @keyup.enter="addData()" class="new-todo" placeholder="What needs to be done?" autofocus>
			</header>
			<!-- This section should be hidden by default and shown when there are todos -->
			<section class="main" v-show="todoList.length ">
				<input v-model="toggleAll" id="toggle-all" class="toggle-all" type="checkbox">
				<label for="toggle-all">Mark all as complete</label>
				<ul class="todo-list">
					<!-- These are here just to show the structure of the list items -->
					<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
					<li :class="{ 'completed':item.completed,editItem,editing:current == item}" v-for="(item,index) in filterTodoList">
						<div class="view">
							<input class="toggle" type="checkbox" v-model="item.completed">
							<label @dblclick="editItem(item)">{{item.content}}</label>
							<button class="destroy" @click="removeItem(index)" ></button>
						</div>
						<input class="edit" :value="current?.content" 	@keyup.esc="cancelEdit()"
						 												@keyup.enter="$event.target.blur()"
						 												@blur="finishEdit(index,item,$event)">
					</li>
				</ul>
			</section>
			<!-- This footer should be hidden by default and shown when there are todos -->
			<footer class="footer" v-show="todoList.length ">
				<!-- This should be `0 items left` by default -->
				<span class="todo-count"><strong>{{ count }}</strong> item {{ count>1?'s':'' }}left</span>
				<!-- Remove this if you don't implement routing -->
				<ul class="filters">
					<li>
						<a class="{'selected':filterStatus=='all'}" href="#/">All</a>
					</li>
					<li>
						<a class="{'selected':filterStatus=='active'}" href="#/active">Active</a>
					</li>
					<li>
						<a class="{'selected':filterStatus=='completed'}" href="#/completed">Completed</a>
					</li>
				</ul>
				<!-- Hidden if no completed items are left ↓ -->
				<button class="clear-completed" @click="removeCompleted">Clear completed</button>
			</footer>
		</section>
		<footer class="info">
			<p>Double-click to edit a todo</p>
			<!-- Remove the below line ↓ -->
			<p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
			<!-- Change this out with your name and url ↓ -->
			<p>Created by <a href="http://todomvc.com">you</a></p>
			<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
		</footer>
</template>
<script setup lang="ts">
import { computed, reactive, ref, toRefs,watch} from 'vue';

interface TodoItem{
	id: number;
	content: String;
	completed: boolean;
}

interface Data{
	todoList: Array<TodoItem>
	content:String
	current:TodoItem  | null
	filterStatus:String
}

//存储数据对应的key
const STORAGE_KEY = 'todo_data'
    //本地存储数据对象
const itemStorage = {
//读数据
        fetch(){
            return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
        },
//持久化数据
        save(items){
            localStorage.setItem(STORAGE_KEY,JSON.stringify(items))
        }
   }


//构建数据
let data:Data = reactive({
	todoList:itemStorage.fetch(),
	content: '',
	current:null,
	filterStatus: 'all'
})
//解构对象
let { todoList,content,current,filterStatus} = {... toRefs(data) }

//添加数据
function addData(){
	//判断是否为空
	if(content.value.trim()){
		todoList.value.push({
			id: new Date().getTime(),
			content: content.value,
			completed: false
		})
		content.value = ''
	}
}
//显示未完成任务的数量
const count = computed(()=>todoList.value.filter(item=>!item.completed).length)

//定义toggleAll计算属性实现复选框功能
const toggleAll = computed({
        //setter方法监听复选框状态更新后就更新未完成的任务状态 
        //count发生变化时会自动调用该方法
        get(){   
            return count.value == 0
        },
        //复选框选中状态发生改变时会触发setter方法
        set(state){
            //迭代每一个任务，将复选框当前状态赋值给每个元素
            data.todoList.forEach(item=>item.completed=state)
        }
    })

//移除任务项
function removeItem(index:number){
       data.todoList.splice(index,1);
    }

//移除所有已完成的任务项
    //filter() 过滤出数组中符合条件的数据
    //splice() 删除数组中的指定元素
    //push() 将一个或多个元素添加到数组的末尾
    //...(三个点)  扩展运算符，用于将一个数组或对象展开，便于数组构造
    function removeCompleted(){
       const t = todoList.value.filter(item => !item.completed)
       data.todoList.splice(0,todoList.value.length)
       data.todoList.push(...t)
	}

	//双击修改任务项
	function editItem(item:TodoItem){
		data.current = item
	}
	//取消编辑
	function cancelEdit(){
		data.current = null
	}
 	//编辑数据
	 function finishEdit(index:number,item:TodoItem,event:any){
        //Esc取消编辑也会自动触发blur事件，直接返回
        if(!data.current) return 
        //如果输入框没有内容，则执行移除操作
        const con = event.target.value.trim()
        if(!con){
            removeItem(index)
            return
        }
        //编辑操作
        item.content = con
        //编辑完成，当前编辑项设置为null,取消.editing样式
        data.current = null
    }

	 //监听地址栏hash值的变化
	 window.onhashchange = function(){
        let hash = window.location.hash.substring(2) || 'all'
        filterStatus.value = hash
   }

   const filterTodoList = computed(() => {
    switch(filterStatus.value){
        case 'active':
            return data.todoList.filter(item => !item.completed)
            break
        case 'completed':
            return data.todoList.filter(item => item.completed)
            break
        default:
            return data.todoList
            break
    }
   })

//监听todoList有改变，就保存最新的数据
watch(todoList.value,()=>{
        console.log('数据变化了')
        itemStorage.save(todoList.value)
    })

</script>
<style>

</style>